﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Xml;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Electric.Controls;
using YArchitech.LIB;
using YArchitech.LIB.YJKControls;
using YArchitech.MEP.Electric.Common;
using YArchitech.Revit;
using YArchitech.Revit.Electric.Common;
using HYFamilyLibDataManager;
using HYPreviewer;

namespace HYRElectric.Equipment
{
	public partial class EquipmentLayoutFormNew : System.Windows.Forms.Form
	{
		[DllImport("user32.dll", CharSet = CharSet.Auto)]
		public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);

		public EquipmentLayoutFormNew(string title, string tableName, List<DbFamilyGroup> groups, int layWays, Dictionary<string, List<Family>> lstFamilyGet, UIApplication application, bool bForSelectSymbol = false)
		{
			this.InitializeComponent();
			this.bIsFamilyLib = true;
			this.formTitle = title;
			this.key = tableName;
			this.familyGroups = groups;
			this.layoutWays = layWays;
			this.layoutWay = EquipmentLayoutWay.Lay_Random;
			this.familyObject = null;
			this.familyObjectCurDoc = null;
			this.familySymbolCurDoc = null;
			this.m_bForSelectSymbol = bForSelectSymbol;
			this.m_doc = application.ActiveUIDocument.Document;
			this.m_application = application;
			this.m_lstFamilyDocGet = lstFamilyGet;
			this.curDocFamily = null;
			this.m_lstFamilyParameter = new Dictionary<Family, List<DbFamilyParameter>>();
			this.InitFamilyParameterInfo();
			this.InitFamilyListByDoc();
			this.picturePreviewFamilyCurves = new HYPreviewer.Previewer(1u);
			this.picturePreviewFamilyCurves.Paint += this.picturePreviewFamilyCurves_Paint;
			base.Controls.Add(this.picturePreviewFamilyCurves);
            this.picturePreviewFamilyCurves.Location = new System.Drawing.Point(this.pbPreviewImage2D.Location.X, this.pbPreviewImage2D.Location.Y);
			this.picturePreviewFamilyCurves.Size = new Size(this.pbPreviewImage2D.Width, this.pbPreviewImage2D.Height);
			this.picturePreviewFamilyCurves.TabStop = false;
		}

		private void InitFamilyParameterInfo()
		{
			List<List<DbFamilyParameter>> list = new List<List<DbFamilyParameter>>();
			foreach (DbFamilyGroup dbFamilyGroup in this.familyGroups)
			{
				if (!string.IsNullOrEmpty(dbFamilyGroup.Image2D) && dbFamilyGroup.FamilyObjects.Count > 0 && File.Exists(dbFamilyGroup.Image2D))
				{
					List<DbFamilyParameter> parameters = dbFamilyGroup.FamilyObjects[0].Parameters;
					list.Add(parameters);
					break;
				}
			}

            if (list.Count == 0) return;

			int num = 0;
			foreach (KeyValuePair<string, List<Family>> keyValuePair in this.m_lstFamilyDocGet)
			{
				string text = keyValuePair.Key;
				List<Family> value = keyValuePair.Value;
				int num2 = num;
				if (num2 >= list.Count)
				{
					num2 = 0;
				}
				List<DbFamilyParameter> list2 = list[num2];
				foreach (Family curFamily in value)
				{
					List<Element> elementsByFamily = this.GetElementsByFamily(curFamily);
					if (elementsByFamily != null)
					{
						List<DbFamilyParameter> list3 = new List<DbFamilyParameter>();
						foreach (DbFamilyParameter dbFamilyParameter in list2)
						{
							DbFamilyParameter dbFamilyParameter2 = new DbFamilyParameter();
							dbFamilyParameter2.Name = dbFamilyParameter.Name;
							dbFamilyParameter2.SharedName = dbFamilyParameter.SharedName;
							dbFamilyParameter2.Value = dbFamilyParameter.Value;
							dbFamilyParameter2.ReadOnly = dbFamilyParameter.ReadOnly;
							dbFamilyParameter2.Unit = dbFamilyParameter.Unit;
							dbFamilyParameter2.Tag = dbFamilyParameter.Tag;
							string text2 = "";
							if (elementsByFamily.Count > 0)
							{
								Parameter parameter = elementsByFamily[elementsByFamily.Count - 1].GetParameter(dbFamilyParameter.SharedName);
								if (parameter != null)
								{
									bool hasValue = parameter.HasValue;
									text2 = parameter.AsString();
									if (text2 == null)
									{
										text2 = parameter.AsValueString();
									}
									if (dbFamilyParameter2.Unit.ToLower() == "mm")
									{
										dbFamilyParameter2.Value = AssistFunc.feetToMM(parameter.AsDouble());
									}
                                    else if (parameter.StorageType == (StorageType)2 && text2.ElementAt(text2.Length - 1) == 'W')
									{
										dbFamilyParameter2.Value = parameter.AsDouble();
										double num3 = parameter.AsDouble() / 10.7639104167097;
										num3 = (double)((int)(num3 * 10.0) / 10);
										dbFamilyParameter2.Value = num3;
									}
									else
									{
										dbFamilyParameter2.Value = text2;
									}
								}
							}
							else
							{
								dbFamilyParameter2.Value = text2;
							}
							list3.Add(dbFamilyParameter2);
						}
						this.m_lstFamilyParameter.Add(curFamily, list3);
					}
				}
				num++;
			}
		}

		private void SetPropertyGridValueByDocFamily()
		{
			if (this.curDocFamily == null || this.bIsFamilyLib)
			{
				return;
			}
			foreach (KeyValuePair<Family, List<DbFamilyParameter>> keyValuePair in this.m_lstFamilyParameter)
			{
				Family family = keyValuePair.Key;
				if (!(this.curDocFamily.Name != family.Name))
				{
					List<DbFamilyParameter> value = keyValuePair.Value;
					HYPropertys hypropertys = new HYPropertys();
					foreach (DbFamilyParameter dbFamilyParameter in value)
					{
						if (!dbFamilyParameter.ReadOnly)
						{
							HYProperty hyproperty = new HYProperty();
							hyproperty.Category = "设备参数";
							hyproperty.Name = dbFamilyParameter.Name;
							hyproperty.DisplayName = (string.IsNullOrEmpty(dbFamilyParameter.Unit) ? dbFamilyParameter.SharedName : (dbFamilyParameter.SharedName + "(" + dbFamilyParameter.Unit + ")"));
							if (dbFamilyParameter.Value != null)
							{
								hyproperty.Value = (string.IsNullOrEmpty(dbFamilyParameter.Value.ToString().Trim()) ? dbFamilyParameter.Value : Convert.ChangeType(dbFamilyParameter.Value, dbFamilyParameter.Tag as Type));
							}
							else
							{
								hyproperty.Value = "";
							}
							hyproperty.ReadOnly = dbFamilyParameter.ReadOnly;
							hyproperty.Tag = dbFamilyParameter;
							hypropertys.Add(hyproperty);
						}
					}
					this.propertyGrid.SelectedObject = hypropertys;
					this.propertyGrid.ExpandAllGridItems();
					this.SetPropertyGridColumnWidth(this.propertyGrid, 100);
					break;
				}
			}
		}

		private List<Element> GetElementsByFamily(Family curFamily)
		{
			if (curFamily == null)
			{
				return null;
			}
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(this.m_doc);
			filteredElementCollector.OfClass(typeof(FamilyInstance));
			filteredElementCollector.WhereElementIsNotElementType();
			List<Element> list = filteredElementCollector.ToElements().ToList<Element>();
			List<Element> list2 = new List<Element>();
			foreach (Element element in list)
			{
				FamilyInstance familyInstance = element as FamilyInstance;
				if (familyInstance != null && familyInstance.Symbol.FamilyName == curFamily.Name)
				{
					list2.Add(familyInstance);
				}
			}
			return list2;
		}

		public EquipmentLayoutWay LayoutWay
		{
			get
			{
				return this.layoutWay;
			}
		}

		public DbFamilyObject FamilyObject
		{
			get
			{
				if (!this.bIsFamilyLib)
				{
					return this.familyObjectCurDoc;
				}
				return this.familyObject;
			}
		}

		public FamilySymbol SelectedFamilySymbol
		{
			get
			{
				if (!this.bIsFamilyLib)
				{
					return this.familySymbolCurDoc;
				}
				return null;
			}
		}

		private void EquipmentLayoutFormNew_Load(object sender, EventArgs e)
		{
			string strFileName = AssistFunc.GetAppRootPath() + "\\Data\\LegendLayoutSelection.xml";
			this.m_lstNode = EquipmentLayoutFormNew.GetXmlNodeByXpath(strFileName);
			string a = this.formTitle;
			if (a == "配电箱" || a == "综合布线" || a == "安防")
			{
				this.radActualSize.Checked = true;
			}
			else
			{
				this.m_bSizeStyle = 0;
				this.ResizeGrid();
			}
            this.Text = this.formTitle;
            this.InitListView();
            this.ReadSettingDataFromXml();
            this.imgW = this.picturePreviewFamilyCurves.Width;
            this.imgH = this.picturePreviewFamilyCurves.Height;
            this.picturePreviewFamilyCurves.Visible = true;
            this.pbPreviewImage2D.Visible = false;
            this.bIsFamilyLib = true;
            this.InitCurDocFamilyList();
            this.SetDefaultItem();
            this.SetLayStyle();
            this.InitSelectStatus();
            if (this.m_bForSelectSymbol)
            {
                this.buttonOk.Text = "选择";
                this.toolStrip1.Enabled = false;
                this.toolStrip2.Enabled = false;
                base.CenterToParent();
            }

            //base.Icon = Resource.YArchitechIcon;

		}

		private void ResizeGrid()
		{
			this.propertyGrid.Height = 228;
			this.propertyGrid.Refresh();
			this.gbxName.Hide();
		}

		private void SetDefaultItem()
		{
			TreeNode treeNode = null;
			try
			{
				TreeNode firstNode = this.tvwCurDocFamilyList.Nodes[0].FirstNode;
				this.AddFamilySymbol(firstNode);
				treeNode = firstNode.FirstNode;
			}
			catch
			{
				treeNode = this.tvwCurDocFamilyList.Nodes[0];
			}
			if (treeNode != null)
			{
				this.tvwCurDocFamilyList.SelectedNode = treeNode;
				this.tvwCurDocFamilyList.Refresh();
				this.ModifyNodeColor();
			}
		}

		private void AddFamilySymbol(TreeNode node)
		{
			if (node.Nodes.Count == 1 && node.Nodes[0].Text == "Temp")
			{
				node.Nodes.Clear();
				DbFamily dbFamily = node.Tag as DbFamily;
				List<string> symbols = dbFamily.Symbols;
				symbols.Sort();
				if (symbols.Count > 0)
				{
					for (int i = 0; i < symbols.Count; i++)
					{
						TreeNode treeNode = new TreeNode();
						treeNode.Text = symbols[i];
						treeNode.Tag = dbFamily;
						node.Nodes.Add(treeNode);
					}
					this.tvwCurDocFamilyList.Refresh();
				}
			}
		}

		private void InitCurDocFamilyList()
		{
			if (this.tvwCurDocFamilyList.Nodes.Count == 0)
			{
				return;
			}
			this.tvwCurDocFamilyList.Nodes[0].Expand();
			if (this.tvwCurDocFamilyList.SelectedNode == null && this.nodeDoc != null)
			{
				this.tvwCurDocFamilyList.SelectedNode = this.nodeDoc;
				this.tvwCurDocFamilyList.Refresh();
				this.ModifyNodeColor();
			}
		}

		private void EquipmentLayoutForm_Shown(object sender, EventArgs e)
		{
			this.SetPropertyGridColumnWidth(this.propertyGrid, 100);
			this.propertyGrid.Invalidate();
		}

		private void InitListView()
		{
			this.lsvLegendFamilyLib.LargeImageList.ImageSize = new Size(75, 75);
			this.lsvLegendFamilyLib.Items.Clear();
			this.lsvLegendFamilyLib.BeginUpdate();
			foreach (DbFamilyGroup dbFamilyGroup in this.familyGroups)
			{
				if (!string.IsNullOrEmpty(dbFamilyGroup.Image2D) && dbFamilyGroup.FamilyObjects.Count > 0 && File.Exists(dbFamilyGroup.Image2D))
				{
					string name = dbFamilyGroup.FamilyObjects[0].Name;
					string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(dbFamilyGroup.Image2D);
					Image image = Image.FromFile(dbFamilyGroup.Image2D);
					this.lsvLegendFamilyLib.LargeImageList.Images.Add(fileNameWithoutExtension, image);
					ListViewItem listViewItem = new ListViewItem();
					listViewItem.Text = name;
					listViewItem.Tag = dbFamilyGroup;
					listViewItem.ImageKey = fileNameWithoutExtension;
					this.lsvLegendFamilyLib.Items.Add(listViewItem);
				}
			}
			this.lsvLegendFamilyLib.EndUpdate();
			if (this.lsvLegendFamilyLib.Items.Count <= 0)
			{
				base.DialogResult = DialogResult.Cancel;
				base.Close();
				return;
			}
			EquipmentLayoutFormNew.SendMessage(this.lsvLegendFamilyLib.Handle, this.LVM_SETICONSPACING, 0, 6881363);
		}

		private void UpdateListbox()
		{
			if (this.lsvLegendFamilyLib.SelectedItems.Count <= 0)
			{
				return;
			}
			DbFamilyGroup dbFamilyGroup = this.lsvLegendFamilyLib.SelectedItems[0].Tag as DbFamilyGroup;
			if (dbFamilyGroup == null)
			{
				return;
			}
			this.lsbFamilySymbol.Items.Clear();
			foreach (DbFamilyObject item in dbFamilyGroup.FamilyObjects)
			{
				this.lsbFamilySymbol.Items.Add(item);
			}
			this.SelectFamily(0);
		}

		private void UpdatePictureBox()
		{
			this.pictureFamilyPicture.Image = null;
			DbFamilyObject dbFamilyObject = this.lsbFamilySymbol.SelectedItem as DbFamilyObject;
			if (dbFamilyObject == null)
			{
				return;
			}
			if (!File.Exists(dbFamilyObject.Image))
			{
				this.pictureFamilyPicture.Image = this.pictureFamilyPicture.InitialImage;
				return;
			}
			this.pictureFamilyPicture.Image = Image.FromFile(dbFamilyObject.Image);
		}

		private void UpdatePropertyGrid(bool flag)
		{
			DbFamilyObject dbFamilyObject = this.lsbFamilySymbol.SelectedItem as DbFamilyObject;
			if (dbFamilyObject == null)
			{
				this.propertyGrid.SelectedObject = null;
				return;
			}
			if (flag)
			{
				this.familyObjectCurDoc = dbFamilyObject;
				HYPropertys hypropertys = this.propertyGrid.SelectedObject as HYPropertys;
				if (hypropertys == null)
				{
					return;
				}
				if (!this.bIsFamilyLib)
				{
					this.familyObjectCurDoc.Parameters.Clear();
				}
				using (List<HYProperty>.Enumerator enumerator = hypropertys.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						HYProperty hyproperty = enumerator.Current;
						DbFamilyParameter dbFamilyParameter = hyproperty.Tag as DbFamilyParameter;
						dbFamilyParameter.Value = hyproperty.Value;
						if (!this.bIsFamilyLib)
						{
							this.familyObjectCurDoc.Parameters.Add(dbFamilyParameter);
						}
					}
					return;
				}
			}
			HYPropertys hypropertys2 = new HYPropertys();
			foreach (DbFamilyParameter dbFamilyParameter2 in dbFamilyObject.Parameters)
			{
				if (!dbFamilyParameter2.ReadOnly)
				{
					hypropertys2.Add(new HYProperty
					{
						Category = "设备参数",
						Name = dbFamilyParameter2.Name,
						DisplayName = (string.IsNullOrEmpty(dbFamilyParameter2.Unit) ? dbFamilyParameter2.SharedName : (dbFamilyParameter2.SharedName + "(" + dbFamilyParameter2.Unit + ")")),
						Value = (string.IsNullOrEmpty(dbFamilyParameter2.Value.ToString().Trim()) ? dbFamilyParameter2.Value : Convert.ChangeType(dbFamilyParameter2.Value, dbFamilyParameter2.Tag as Type)),
						ReadOnly = dbFamilyParameter2.ReadOnly,
						Tag = dbFamilyParameter2
					});
				}
			}
			this.propertyGrid.SelectedObject = hypropertys2;
			this.propertyGrid.ExpandAllGridItems();
			this.SetPropertyGridColumnWidth(this.propertyGrid, 100);
		}

		private void SetPropertyGridColumnWidth(PropertyGrid grid, int width)
		{
			if (grid == null)
			{
				return;
			}
            System.Windows.Forms.Control control = (System.Windows.Forms.Control)grid.GetType().GetField("gridView", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(grid);
			if (control == null)
			{
				return;
			}
			FieldInfo field = control.GetType().GetField("labelWidth", BindingFlags.Instance | BindingFlags.NonPublic);
			if (null == field)
			{
				return;
			}
			field.SetValue(control, width);
			control.Invalidate();
		}

		private void ReadSettingDataFromXml()
		{
            string pathXml = @"C:\Hongye\HYRME2018\Data\" + "ElectricEquipment.xml";
            YArchitech.MEP.Electric.Common.XmlHelper xmlHelper = new YArchitech.MEP.Electric.Common.XmlHelper(pathXml, "ElectricData");
			string path = "EquipmentLayout\\" + this.key;
			xmlHelper.SelectNode(path);
			int index = Convert.ToInt32(xmlHelper.GetAttributeEx("LayoutWay", "0"));
			this.SelectLayoutWay(index);
			index = Convert.ToInt32(xmlHelper.GetAttributeEx("Legend", "0"));
			this.SelectLegend(index);
			index = Convert.ToInt32(xmlHelper.GetAttributeEx("Family", "0"));
			this.SelectFamily(index);
			string attributeEx = xmlHelper.GetAttributeEx("Size", "0");
			if (!(attributeEx == "0"))
			{
				if (!(attributeEx == "1"))
				{
					if (attributeEx == "2")
					{
						if (this.radActualSize.Enabled)
						{
							this.radActualSize.Checked = true;
						}
					}
				}
				else if (this.radFixSize.Enabled)
				{
					this.radFixSize.Checked = true;
				}
			}
			int x = 0;
			int y = 0;
            try
            {
                x = Convert.ToInt32(xmlHelper.GetAttribute("X"));
                y = Convert.ToInt32(xmlHelper.GetAttribute("Y"));
            }
            catch
            {
                x = 0;
                y = 0;
            }
            System.Drawing.Point location = new System.Drawing.Point(x, y);
			base.Location = location;
		}

		private void SaveSettingDataToXml()
		{

            string pathXml = @"C:\Hongye\HYRME2018\Data\" + "ElectricEquipment.xml";

            YArchitech.MEP.Electric.Common.XmlHelper xmlHelper = new YArchitech.MEP.Electric.Common.XmlHelper(pathXml, "ElectricData");
			string path = "EquipmentLayout\\" + this.key;
			xmlHelper.SelectNode(path);
			xmlHelper.SetAttribute("LayoutWay", this.GetLayoutWay().ToString());
			int num = 0;
			if (this.lsvLegendFamilyLib.SelectedItems.Count > 0)
			{
				num = this.lsvLegendFamilyLib.SelectedItems[0].Index;
			}
			xmlHelper.SetAttribute("Legend", num.ToString());
			xmlHelper.SetAttribute("Family", this.lsbFamilySymbol.SelectedIndex.ToString());
			xmlHelper.SetAttribute("Size", this.m_bSizeStyle.ToString());
			xmlHelper.SetAttribute("X", base.Location.X.ToString());
			xmlHelper.SetAttribute("Y", base.Location.Y.ToString());
			xmlHelper.SaveXml("");
		}

		private void SelectLayoutWay(int index)
		{
			this.layoutWay = (EquipmentLayoutWay)index;
			if (this.layoutWay == (EquipmentLayoutWay)0)
			{
				this.layoutWay = EquipmentLayoutWay.Lay_Random;
			}
			this.SetLayStyle();
		}

		private int GetLayoutWay()
		{
			return (int)this.layoutWay;
		}

		private void SelectLegend(int index)
		{
			if (this.lsvLegendFamilyLib.Items.Count <= 0)
			{
				return;
			}
			if (index < 0 || index >= this.lsvLegendFamilyLib.Items.Count)
			{
				index = 0;
			}
			this.lsvLegendFamilyLib.Items[index].Selected = true;
			this.lsvLegendFamilyLib.EnsureVisible(index);
		}

		private void SelectFamily(int index)
		{
			if (this.lsbFamilySymbol.Items.Count <= 0)
			{
				return;
			}
			if (index < 0 || index >= this.lsbFamilySymbol.Items.Count)
			{
				index = 0;
			}
			this.lsbFamilySymbol.SelectedIndex = index;
		}

		private void lsvLegend_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.UpdateListbox();
		}

		private void lsbFamily_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.UpdatePictureBox();
			this.UpdatePropertyGrid(false);
			string text = this.lsvLegendFamilyLib.SelectedItems[0].Text;
			if (this.m_lstNode.Contains(text))
			{
				this.radActualSize.Enabled = true;
				this.radFixSize.Enabled = true;
				if (this.m_bSizeStyle == 0)
				{
					this.radFixSize.Checked = true;
					return;
				}
			}
			else
			{
				this.radActualSize.Enabled = false;
				this.radActualSize.Checked = false;
				this.radFixSize.Enabled = false;
				this.radFixSize.Checked = false;
				this.m_bSizeStyle = 0;
			}
		}

		private void buttonOk_Click(object sender, EventArgs e)
		{
			this.UpdatePropertyGrid(true);
			this.familyObject = (this.lsbFamilySymbol.SelectedItem as DbFamilyObject);
			this.familyObject.Size = this.m_bSizeStyle;
			this.familyObjectCurDoc = this.familyObject;
			this.SaveSettingDataToXml();
			if (!this.bIsFamilyLib)
			{
				this.familyObjectCurDoc.Name = this.curDocFamily.Name;
				this.familyObjectCurDoc.Family = this.curDocFamily.Name;
			}
			base.DialogResult = DialogResult.OK;
		}

		private void tvwCurDocFamilyList_DoubleClick(object sender, EventArgs e)
		{
			if (2 == this.tvwCurDocFamilyList.SelectedNode.Level)
			{
				this.buttonOk_Click(sender, e);
			}
		}

		private void propertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
		{
			if (e == null)
			{
				return;
			}
			GridItem changedItem = e.ChangedItem;
			if (changedItem == null)
			{
				return;
			}
			string label = changedItem.Label;
			List<string> list = new List<string>();
			list.Add("功率(W)");
			list.Add("功率系数");
			list.Add("额定电流(A)");
			if (this.layoutWay == EquipmentLayoutWay.Lay_SwitchBoxes)
			{
				foreach (string b in new List<string>
				{
					"宽度(mm)",
					"高度(mm)",
					"厚度(mm)"
				})
				{
					if (!(label != b))
					{
						string value = changedItem.Value.ToString();
						if (string.IsNullOrEmpty(value))
						{
							this.SetPropertyValue(label, e.OldValue);
							return;
						}
						if (Convert.ToDouble(value) < 100.0)
						{
							this.SetPropertyValue(label, e.OldValue);
							return;
						}
					}
				}
			}
			foreach (string b2 in list)
			{
				if (!(label != b2) && !Assist.StringUtil.isNumberic2(changedItem.Value.ToString()))
				{
					this.SetPropertyValue(label, e.OldValue);
					return;
				}
			}
			if (label == "功率系数")
			{
				double num = Convert.ToDouble(changedItem.Value);
				if (num < 0.0 || num > 1.0)
				{
					this.SetPropertyValue(label, e.OldValue);
				}
			}
		}

		private void SetPropertyValue(string name, object value)
		{
			HYPropertys hypropertys = this.propertyGrid.SelectedObject as HYPropertys;
			if (hypropertys == null)
			{
				return;
			}
			foreach (HYProperty hyproperty in hypropertys)
			{
				if (hyproperty.DisplayName == name)
				{
					hyproperty.Value = value;
					break;
				}
			}
		}

		private void SetPropertyValue(string name, string value)
		{
			HYPropertys hypropertys = (HYPropertys)this.propertyGrid.SelectedObject;
			if (hypropertys == null)
			{
				return;
			}
			if (!hypropertys.Exists((HYProperty item) => item.DisplayName == name))
			{
				return;
			}
			hypropertys.Find((HYProperty item) => item.DisplayName == name).Value = value;
		}

		private void InitSelectStatus()
		{
			this.lsvLegendFamilyLib.Visible = this.bIsFamilyLib;
			this.pictureFamilyPicture.Visible = this.bIsFamilyLib;
			this.lsbFamilySymbol.Visible = this.bIsFamilyLib;
			this.elementHost3dSolid.Visible = !this.bIsFamilyLib;
			this.tvwCurDocFamilyList.Visible = !this.bIsFamilyLib;
			this.labelRemark.Visible = !this.bIsFamilyLib;
			this.pbPreviewImage2D.Visible = !this.bIsFamilyLib;
			this.picturePreviewFamilyCurves.Visible = !this.bIsFamilyLib;
			this.listCurDocFamilyName.Visible = !this.bIsFamilyLib;
			if (!this.bIsFamilyLib)
			{
				this.pbPreviewImage2D.Visible = (this.legend == null);
				this.picturePreviewFamilyCurves.Visible = (this.legend != null);
			}
		}

		private void rdoFamilyLib_CheckedChanged(object sender, EventArgs e)
		{
			this.bIsFamilyLib = true;
			this.InitSelectStatus();
			this.UpdateListbox();
		}

		private void rdoCurrentDoc_CheckedChanged(object sender, EventArgs e)
		{
			this.radActualSize.Enabled = false;
			this.radActualSize.Checked = false;
			this.radFixSize.Enabled = false;
			this.radFixSize.Checked = false;
			this.m_bSizeStyle = 0;
			this.bIsFamilyLib = false;
			this.InitSelectStatus();
			if (this.curDocFamily != null)
			{
				this.SetPropertyGridValueByDocFamily();
			}
		}

		private void ModifyNodeColor()
		{
			TreeNode selectedNode = this.tvwCurDocFamilyList.SelectedNode;
			if (selectedNode != null)
			{
                selectedNode.BackColor = System.Drawing.Color.RoyalBlue;
                selectedNode.ForeColor = System.Drawing.Color.White;
			}
		}

		private void tvwFamilyList_BeforeSelect(object sender, TreeViewCancelEventArgs e)
		{
			TreeNode selectedNode = this.tvwCurDocFamilyList.SelectedNode;
			if (selectedNode != null)
			{
                selectedNode.BackColor = System.Drawing.Color.Empty;
                selectedNode.ForeColor = System.Drawing.Color.Black;
			}
		}

		private void tvwFamilyList_Leave(object sender, EventArgs e)
		{
			this.ModifyNodeColor();
		}

		private void tvwFamilyList_AfterSelect(object sender, TreeViewEventArgs e)
		{
			if (this.bCollapse)
			{
				return;
			}
			this.GetNodeImage(e);
			this.UpdateListSymbolCurDoc(e);
		}

		private void tvwCurDocFamilyList_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
		{
			this.bCollapse = true;
		}

		private void tvwCurDocFamilyList_AfterCollapse(object sender, TreeViewEventArgs e)
		{
			this.bCollapse = false;
		}

		private void GetNodeImage(TreeViewEventArgs e)
		{
			TreeNode treeNode = e.Node;
			this.nodeDoc = treeNode;
			if (treeNode.Level == 1)
			{
				treeNode = treeNode.LastNode;
			}
			if (treeNode.Level == 2)
			{
				if (treeNode.Tag is FamilySymbol)
				{
					FamilySymbol familySymbol = (FamilySymbol)treeNode.Tag;
					Document doc = this.m_doc.EditFamily(familySymbol.Family);
					this.Update3DView(doc);
					this.Refresh2DImg(doc, familySymbol, this.m_application);
					return;
				}
			}
			else if (treeNode.Level == 1 && treeNode.FirstNode.Tag is FamilySymbol)
			{
				FamilySymbol familySymbol2 = (FamilySymbol)treeNode.FirstNode.Tag;
				Document doc2 = this.m_doc.EditFamily(familySymbol2.Family);
				this.Update3DView(doc2);
				this.Refresh2DImg(doc2, familySymbol2, this.m_application);
			}
		}

		private void UpdateListSymbolCurDoc(TreeViewEventArgs e)
		{
			TreeNode node = e.Node;
			Family family = null;
			if (node.Tag is Family)
			{
				family = (Family)node.Tag;
				this.familySymbolCurDoc = null;
			}
			else if (node.Tag is FamilySymbol)
			{
				FamilySymbol familySymbol = (FamilySymbol)node.Tag;
				if (familySymbol != null)
				{
					family = familySymbol.Family;
					this.familySymbolCurDoc = familySymbol;
				}
			}
			if (family != null)
			{
				this.listCurDocFamilyName.Items.Clear();
				this.listCurDocFamilyName.Items.Add(family.Name);
				this.listCurDocFamilyName.SelectedIndex = 0;
				this.curDocFamily = family;
				if (!this.bIsFamilyLib)
				{
					this.SetPropertyGridValueByDocFamily();
				}
			}
		}

        public static Autodesk.Revit.DB.View GetReferenceView(Document sourceDocument)
		{
            FilteredElementIterator elementIterator = new FilteredElementCollector(sourceDocument).OfClass(typeof(Autodesk.Revit.DB.View)).GetElementIterator();
			elementIterator.Reset();
            Autodesk.Revit.DB.View view = null;
			while (elementIterator.MoveNext())
			{
				Element element = elementIterator.Current;
                Autodesk.Revit.DB.View view2 = element as Autodesk.Revit.DB.View;
                if (view2 != null && !view2.IsTemplate && view2.ViewType == (ViewType)1)
				{
					view = view2;
					break;
				}
			}
			if (view == null)
			{
				elementIterator.Reset();
				while (elementIterator.MoveNext())
				{
					Element element2 = elementIterator.Current;
                    Autodesk.Revit.DB.View view3 = element2 as Autodesk.Revit.DB.View;
					if (view3 != null && !view3.IsTemplate && view3.ViewType == (ViewType)2)
					{
						view = view3;
						break;
					}
				}
			}
			if (view == null)
			{
				elementIterator.Reset();
				while (elementIterator.MoveNext())
				{
					Element element3 = elementIterator.Current;
                    Autodesk.Revit.DB.View view4 = element3 as Autodesk.Revit.DB.View;
					if (view4 != null && !view4.IsTemplate && view4.ViewType == (ViewType)7)
					{
						view = view4;
						break;
					}
				}
			}
			return view;
		}

		private List<Family> GetInnerFamily(UIApplication uiApp, Document sourceDocument)
		{
			List<Family> list = new List<Family>();
			try
			{
				new HYPreviewer.Legend();
				new List<HYPreviewer.CurveInfo>();
                Autodesk.Revit.DB.View referenceView = EquipmentLayoutFormNew.GetReferenceView(sourceDocument);
				if (referenceView == null)
				{
					return null;
				}
				foreach (Element element in new FilteredElementCollector(sourceDocument, referenceView.Id).ToElements())
				{
					if (element is FamilyInstance && element.Category.Id.IntegerValue == -2000150)
					{
						list.Add((element as FamilyInstance).Symbol.Family);
					}
				}
			}
			catch (Exception)
			{
			}
			return list;
		}

		private void Refresh2DImg(Document doc, FamilySymbol fs, UIApplication application)
		{
			List<Family> innerFamily = this.GetInnerFamily(application, doc);
			if (innerFamily.Count == 0)
			{
				innerFamily.Add(fs.Family);
			}
			foreach (Family family in innerFamily)
			{
				Document sourceDocument = doc.EditFamily(family);
				this.legend = HYPreviewer.LegendCommon.GetFamily2DImg(application, sourceDocument);
				if (this.legend != null)
				{
					break;
				}
			}
			if (this.legend == null)
			{
				this.legend = HYPreviewer.LegendCommon.GetFamily2DImg(application, doc);
			}
			if (this.legend != null)
			{
				this.picturePreviewFamilyCurves.Visible = true;
				this.pbPreviewImage2D.Visible = false;
				this.picturePreviewFamilyCurves.Refresh();
				return;
			}
			this.pbPreviewImage2D.Image = fs.GetPreviewImage(new Size(this.imgW, this.imgH));
			this.pbPreviewImage2D.Visible = true;
			this.picturePreviewFamilyCurves.Visible = false;
		}

		private void picturePreviewFamilyCurves_Paint(object sender, PaintEventArgs e)
		{
			Graphics graphics = e.Graphics;
            graphics.Clear(System.Drawing.Color.White);
			this.RefreshPreview(graphics);
		}

		private void RefreshPreview(Graphics g)
		{
			try
			{
				this.picturePreviewFamilyCurves.Curves = this.legend.Curves;
				this.picturePreviewFamilyCurves.FillRegions = this.legend.FillRegions;
				this.picturePreviewFamilyCurves.TextNotes = this.legend.Texts;
				this.picturePreviewFamilyCurves.ZoomExtents();
			}
			catch (Exception)
			{
			}
		}

		private void Update3DView(Document doc)
		{
			PreviewControl previewControl = this.elementHost3dSolid.Child as PreviewControl;
			if (doc == null)
			{
				if (previewControl != null)
				{
					previewControl.Dispose();
					previewControl = null;
				}
				return;
			}
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
            filteredElementCollector.OfClass(typeof(Autodesk.Revit.DB.View));
            IEnumerable<Autodesk.Revit.DB.View> enumerable = from Element f in filteredElementCollector
                                                             where (f as Autodesk.Revit.DB.View).CanBePrinted
                                                             select f as Autodesk.Revit.DB.View;
            Autodesk.Revit.DB.View view = null;
            foreach (Autodesk.Revit.DB.View view2 in enumerable)
			{
				if (view2.ViewType == (ViewType)4 && view2.Name == "{3D}")
				{
					view = view2;
					break;
				}
			}
			if (view == null)
			{
                foreach (Autodesk.Revit.DB.View view3 in enumerable)
				{
					if (view3.ViewType == (ViewType)4)
					{
						view = view3;
						break;
					}
				}
			}
			if (view == null)
			{
                foreach (Autodesk.Revit.DB.View view4 in enumerable)
				{
					if (view4.ViewType == (ViewType)1)
					{
						view = view4;
						break;
					}
				}
			}
			if (view == null)
			{
				if (previewControl != null)
				{
					previewControl.Dispose();
					previewControl = null;
				}
				return;
			}
			if (previewControl != null)
			{
				previewControl.Dispose();
			}
			this.elementHost3dSolid.Child = new PreviewControl(doc, view.Id);
		}

		private void Update3DView1(Document doc)
		{
			PreviewControl previewControl = this.elementHost3dSolid.Child as PreviewControl;
			if (doc == null)
			{
				if (previewControl != null)
				{
					previewControl.Dispose();
					previewControl = null;
				}
				return;
			}
            Autodesk.Revit.DB.View view = HYPreviewer.LegendCommon.GetReferenceView(doc);
			IEnumerable<Element> enumerable = new FilteredElementCollector(doc, view.Id).ToElements();
			List<Element> list = new List<Element>();
			foreach (Element element in enumerable)
			{
				if (element is FamilyInstance && element.Category.Id.IntegerValue == -2000150)
				{
					list.Add(element);
				}
			}
			if (previewControl != null)
			{
				previewControl.Dispose();
			}
			if (list.Count == 0)
			{
				return;
			}
			doc = this.m_doc.EditFamily((list[0] as FamilyInstance).Symbol.Family);
			view = this.GetProjectBrowserView(doc);
			this.elementHost3dSolid.Child = new PreviewControl(doc, view.Id);
		}

        public Autodesk.Revit.DB.View GetProjectBrowserView(Document sourceDocument)
		{
            FilteredElementIterator elementIterator = new FilteredElementCollector(sourceDocument).OfClass(typeof(Autodesk.Revit.DB.View)).GetElementIterator();
			elementIterator.Reset();
			while (elementIterator.MoveNext())
			{
				Element element = elementIterator.Current;
                Autodesk.Revit.DB.View view = element as Autodesk.Revit.DB.View;
				if (view != null && !view.IsTemplate)
				{
					return view;
				}
			}
			return null;
		}

		private void InitFamilyListByDoc()
		{
			this.tvwCurDocFamilyList.Nodes.Clear();
			foreach (KeyValuePair<string, List<Family>> keyValuePair in this.m_lstFamilyDocGet)
			{
				string text = keyValuePair.Key;
				List<Family> value = keyValuePair.Value;
				TreeNode treeNode = this.tvwCurDocFamilyList.Nodes.Add(text);
				foreach (Family family in value)
				{
					TreeNode treeNode2 = new TreeNode();
					treeNode2.Text = family.Name;
					treeNode2.Tag = family;
					foreach (FamilySymbol familySymbol in (from ff in family.GetSymbols()
					orderby ff.Name
					select ff).ToList<FamilySymbol>())
					{
						TreeNode treeNode3 = new TreeNode();
						treeNode3.Text = familySymbol.Name;
						treeNode3.Tag = familySymbol;
						treeNode2.Nodes.Add(treeNode3);
					}
					treeNode.Nodes.Add(treeNode2);
				}
				treeNode.Expand();
			}
		}

		private void tvwFamilyList_AfterExpand(object sender, TreeViewEventArgs e)
		{
			TreeNode node = e.Node;
			bool @checked = this.rdoFamilyLib.Checked;
			if (@checked && node.Level == 1)
			{
				this.AddFamilySymbol(node);
			}
		}

		private void SetLayStyle()
		{
			this.btnLay_Random.Checked = (this.layoutWay == EquipmentLayoutWay.Lay_Random);
			this.btnLay_DragLine.Checked = (this.layoutWay == EquipmentLayoutWay.Lay_DragLine);
			this.btnLay_DragLineEx.Checked = (this.layoutWay == EquipmentLayoutWay.Lay_DragLineEx);
			this.btnLay_Rect.Checked = (this.layoutWay == EquipmentLayoutWay.Lay_Rect);
			this.btnLay_RectEx.Checked = (this.layoutWay == EquipmentLayoutWay.Lay_RectEx);
			this.btnLay_ArcLine.Checked = (this.layoutWay == EquipmentLayoutWay.Lay_ArcLine);
			this.btnLay_Fan.Checked = (this.layoutWay == EquipmentLayoutWay.Lay_Fan);
			this.btnLay_WallCross.Checked = (this.layoutWay == EquipmentLayoutWay.Lay_WallCross);
			this.btnLay_RoomCenter.Checked = (this.layoutWay == EquipmentLayoutWay.Lay_CenterRoom);
		}

		private void btnLay_Random_Click(object sender, EventArgs e)
		{
			this.layoutWay = EquipmentLayoutWay.Lay_Random;
			this.SetLayStyle();
		}

		private void btnLay_DragLine_Click(object sender, EventArgs e)
		{
			this.layoutWay = EquipmentLayoutWay.Lay_DragLine;
			this.SetLayStyle();
		}

		private void btnLay_DragLineEx_Click(object sender, EventArgs e)
		{
			this.layoutWay = EquipmentLayoutWay.Lay_DragLineEx;
			this.SetLayStyle();
		}

		private void btnLay_Rect_Click(object sender, EventArgs e)
		{
			this.layoutWay = EquipmentLayoutWay.Lay_Rect;
			this.SetLayStyle();
		}

		private void btnLay_RectEx_Click(object sender, EventArgs e)
		{
			this.layoutWay = EquipmentLayoutWay.Lay_RectEx;
			this.SetLayStyle();
		}

		private void btnLay_ArcLine_Click(object sender, EventArgs e)
		{
			this.layoutWay = EquipmentLayoutWay.Lay_ArcLine;
			this.SetLayStyle();
		}

		private void btnLay_Fan_Click(object sender, EventArgs e)
		{
			this.layoutWay = EquipmentLayoutWay.Lay_Fan;
			this.SetLayStyle();
		}

		private void btnLay_WallCross_Click(object sender, EventArgs e)
		{
			this.layoutWay = EquipmentLayoutWay.Lay_WallCross;
			this.SetLayStyle();
		}

		private void btnLay_RoomCenter_Click(object sender, EventArgs e)
		{
			this.layoutWay = EquipmentLayoutWay.Lay_CenterRoom;
			this.SetLayStyle();
		}

		private void radFixSize_CheckedChanged(object sender, EventArgs e)
		{
			if (this.radFixSize.Checked)
			{
				this.m_bSizeStyle = 1;
			}
		}

		private void radActualSize_CheckedChanged(object sender, EventArgs e)
		{
			if (this.radActualSize.Checked)
			{
				this.m_bSizeStyle = 2;
			}
		}

		private static List<string> GetXmlNodeByXpath(string strFileName)
		{
			List<string> list = new List<string>();
			XmlDocument xmlDocument = new XmlDocument();
			try
			{
				xmlDocument.Load(strFileName);
				foreach (object obj in xmlDocument.DocumentElement.ChildNodes)
				{
					XmlElement xmlElement = (XmlElement)obj;
					if (xmlElement.Name == "Cell")
					{
						list.Add(xmlElement.LastChild.Value);
					}
				}
			}
			catch
			{
			}
			return list;
		}

		private string key;

		private string formTitle;

		private int layoutWays;

		private List<DbFamilyGroup> familyGroups;

		private DbFamilyObject familyObject;

		private DbFamilyObject familyObjectCurDoc;

		private FamilySymbol familySymbolCurDoc;

		private Document m_doc;

		private UIApplication m_application;

		private const string XmlNode_LayoutWay = "LayoutWay";

		private const string XmlNode_Legend = "Legend";

		private const string XmlNode_Family = "Family";

		private const string XmlNode_SizeStyle = "Size";

		private const int GridColWidth = 100;

		private int LVM_SETICONSPACING = 4149;

		private TreeNode nodesDoc;

		private TreeNode nodeDoc;

		private int imgW;

		private int imgH;

		private HYPreviewer.Previewer picturePreviewFamilyCurves;

		private HYPreviewer.Legend legend;

		public bool bIsFamilyLib;

		private Dictionary<string, List<Family>> m_lstFamilyDocGet;

		private Dictionary<Family, List<DbFamilyParameter>> m_lstFamilyParameter;

		private Family curDocFamily;

		private bool m_bForSelectSymbol;

		public int m_bSizeStyle;

		private List<string> m_lstNode = new List<string>();

		private EquipmentLayoutWay layoutWay;

		private bool bCollapse;
	}
}
